/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.zprofilefrontend.model;

import com.vng.zing.calc.thrift.Profile;
import com.vng.zing.calc.thrift.ProfileSession;
import com.vng.zing.calc.thrift.ROLE;
import com.vng.zing.configer.ZConfig;
import com.vng.zing.logger.ZLogger;
import com.vng.zing.stats.monitor.common.TemplateManager;
import com.vng.zing.zprofile.thrift.wrapper.ZProfileClient;
import com.vng.zing.zprofile.thrift.wrapper.ZProfileClientInstance;
import com.vng.zing.zprofile.thrift.wrapper.ZProfileClientWithCache;
import com.vng.zing.zprofilefrontend.common.Properties;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import hapax.TemplateException;
import java.io.PrintWriter;
import javax.servlet.SessionCookieConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SessionManager;

/**
 * @Note: Class base model xử lý business chung & hàm tiện ích cho tất cả
 * handler/controller, các model chính được thừa kế từ base model này
 *
 * @author namnq
 */
public abstract class BaseModel {

    protected static ZConfig config = ZConfig.Instance;

    private static final Logger _Logger = ZLogger.getLogger(BaseModel.class);

    public abstract void process(HttpServletRequest req, HttpServletResponse resp);

    private static final ZProfileClientInstance _INSTANCE = ZProfileClientInstance.getInstance();
    private static final Properties properties = Properties.getInstance();

    protected Properties getProperties() {
        return properties;
    }

    protected ZProfileClient getClient() {
        return _INSTANCE.getClient();
    }

    protected ZProfileClientWithCache getClientWithCache() {
        return _INSTANCE.getClientWithCache();
    }

    /**
     * outAndClose: print data to client
     *
     * @param req
     * @param resp
     * @param content: String will be produced by content.toString()
     * @return
     */
    /**
     * outAndClose: print data to client
     *
     * @param req
     * @param resp
     * @param content : String will be produced by content.toString()
     * @return
     */
    protected boolean outAndClose(HttpServletRequest req, HttpServletResponse resp, Object content) {
        boolean result = false;
        PrintWriter out = null;
        try {
            out = resp.getWriter();
            out.print(content);
            result = true;
        } catch (Exception ex) {
            _Logger.error(ex.getMessage() + " while processing URI \"" + req.getRequestURI() + "?" + req.getQueryString() + "\"", ex);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return result;
    }

    /**
     * prepareHeaderHtml: set http header for html content (text/html;
     * charset=UTF-8)
     *
     * @param resp
     */
    protected void prepareHeaderHtml(HttpServletResponse resp) {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
    }

    /**
     * prepareHeaderJs: set http header for javascript content (text/javascript;
     * charset=UTF-8)
     *
     * @param resp
     */
    protected void prepareHeaderJs(HttpServletResponse resp) {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/javascript; charset=UTF-8");
    }

    protected void setHeaderFooter(String pageTitle, TemplateDataDictionary dic, Profile profile) {
        try {
            Template header = TemplateManager.getTemplate("header");
            TemplateDataDictionary headerDic = TemplateDictionary.create();
            Template footer = TemplateManager.getTemplate("footer");

            if (null != profile) {
                TemplateDataDictionary loginBarDic = TemplateDictionary.create();
                Template loginBar;
                if (ROLE.ADMIN.equals(profile.getRole())) {
                    loginBar = TemplateManager.getTemplate("admin-bar");
                } else {
                    loginBar = TemplateManager.getTemplate("login-bar");
                }
                loginBarDic.setVariable("NAME", (null != profile.getDisplayName() && !"".equals(profile.getDisplayName()) ? profile.getDisplayName() : profile.getUsername()));
                loginBarDic.setVariable("PROFILE_ID", String.format("%s", profile.id));
                headerDic.setVariable("LOGIN_BAR", loginBar.renderToString(loginBarDic));
            }
            headerDic.setVariable("PAGE_TITLE", pageTitle);

            dic.setVariable("HEADER", header.renderToString(headerDic));
            dic.setVariable("FOOTER", footer.renderToString(TemplateDictionary.create()));
        } catch (TemplateException ex) {
            _Logger.error("set header and footer " + ex.toString());
        }
    }

    protected static ProfileSession checkLogIn(HttpServletRequest req) {
        Request base_request = (Request) req;
        HttpSession session = base_request.getSession(false);
        if (null != session && null != session.getAttribute("profile")) {
            return (ProfileSession) session.getAttribute("profile");
        }
        return null;
    }

    protected void setLoggedIn(HttpServletRequest req, HttpServletResponse resp, ProfileSession profileSession, boolean isRememberme) {
        Request base_request = (Request) req;
        SessionManager sessionManager = base_request.getSessionManager();
        SessionCookieConfig cookieConfig = sessionManager.getSessionCookieConfig();
        cookieConfig.setHttpOnly(true);
        if ( profileSession.getExpAccessTokenTime() > 0) {
            cookieConfig.setMaxAge(profileSession.getExpAccessTokenTime());
        } else {
            if (isRememberme) {
                cookieConfig.setMaxAge(config.getInt("cookie.expTime", 86400));
            }
        }
        HttpSession session = base_request.getSession(true);
        session.setAttribute("profile", profileSession);
    }

    protected void showError(PrintWriter out, String message) {
        try {
            TemplateDataDictionary dic = TemplateDictionary.create();
            setHeaderFooter("ZProfile - Error", dic, null);
            dic.setVariable("MESSAGE", message);
            Template error = TemplateManager.getTemplate("message");
            out.println(error.renderToString(dic));
        } catch (TemplateException ex) {
            _Logger.error("showError " + ex.toString());
        }
    }

//    public static String getCookieValue(HttpServletRequest request, String name) {
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null) {
//            for (Cookie cookie : cookies) {
//                if (name.equals(cookie.getName())) {
//                    return cookie.getValue();
//                }
//            }
//        }
//        return null;
//    }
//
//    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
//        Cookie cookie = new Cookie(name, value);
//        cookie.setPath("/");
//        cookie.setMaxAge(maxAge);
//        response.addCookie(cookie);
//    }
//
//    public static void removeCookie(HttpServletResponse response, String name) {
//        addCookie(response, name, null, 0);
//    };
}
